/**
 * Created by TomSean on 2017/12/13.
 */
var InspectionManager = function ($parent) {
    this.sysUtils = new kendoUtils();
    this.$parent = $parent;
    this.init();
    return this;
}

InspectionManager.prototype = {
    init : function () {
        var $this = this;
        var fieldArray = $this.sysUtils.getBindFieldArray($this.$parent.find('.search-panel'));
        var functionArray = [
            {fName : 'find_data', fs : $this.findData},
            {fName : 'primary_data', fs : $this.primaryData},
            {fName : 'correct_data', fs : $this.correctData},
            {fName : 'cancel_data', fs : $this.cancelData},
            {fName : 'search_image', fs : $this.searchImage},
            {fName : 'search_vehicle', fs : $this.searchVehicle},
            {fName : 'nextData',fs:$this.nextData},
            {fName : 'reset', fs : $this.reset},
        ];
        $this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        $this.sysUtils.bindDoucment($this.models, $this.$parent, $this);

        var provinceMap = new Map();
        provinceMap.put('j', ['京','津','冀','晋','吉']);
        provinceMap.put('y', ['粤','渝','豫','云']);
        provinceMap.put('l', ['鲁','辽']);
        provinceMap.put('m', ['蒙','闽']);
        provinceMap.put('h', ['沪','黑']);
        provinceMap.put('s', ['苏','陕']);
        provinceMap.put('z', ['浙','藏']);
        provinceMap.put('g', ['贵','桂','赣','甘']);
        provinceMap.put('n', ['宁']);
        provinceMap.put('x', ['湘','新']);
        provinceMap.put('q', ['琼','青']);
        provinceMap.put('e', ['鄂']);
        provinceMap.put('w', ['皖']);
        provinceMap.put('c', ['川']);
        $this.provinceMap = provinceMap;

        $this.$parent.find('#vehicle-number-type').bind('change', function(e) {
            var inputList = '<input type="text" maxlength="1" onkeydown="inspectionManager.limitProvince(this, event)" />';
            $this.$parent.find('.numberInto input[type="text"]').remove();
            var len = 0;
            if ($(this).val() == 0) {
                len = 6;
            } else if ($(this).val() == 1) {
                len = 7;
            } else if ($(this).val() == 2) {
                len = 6;
            }
            for (var i = 0; i < len; i++) {
                inputList += '<input type="text" maxlength="1" onkeydown="inspectionManager.limitVehicleNumber(this, event)" />';
            }
            $this.$parent.find('.numberInto').prepend(inputList);
        });

        $this.$parent.find('#before-record-count input[type="number"]').bind('focus', function (e) {
            $this.$parent.find('#before-record-count button').removeClass('action');
            $this.$parent.find('#before-record-count input[type="number"]').addClass('action');
        }).bind('blur', function () {
            if (isEmpty($(this).val()) || isNaN($(this).val())) {
                $(this).val(5);
            }
            $this.beforeCount = $(this).val();
            $this.searchVehicle();
        });

        $this.$parent.find('#after-record-count input[type="number"]').bind('focus', function (e) {
            $this.$parent.find('#after-record-count button').removeClass('action');
            $this.$parent.find('#after-record-count input[type="number"]').addClass('action');
        }).bind('blur', function () {
            if (isEmpty($(this).val()) || isNaN($(this).val())) {
                $(this).val(5);
            }
            $this.afterCount = $(this).val();
            $this.searchVehicle();
        });

        $this.$parent.find('[name="display_record_status"]').bind('change', function (e) {
            $this.findData();
        });

        JsonpAjax(baseApiPath + 'recordMarket/inspection/space/count', '', 'json', function (res) {
            $this.$parent.find('#now_car').html(res.nowCount);
        });

        // 加载组织结构
        JsonpAjax(baseApiPath + 'recordMarket/inspection/organization/tree', '', 'json', function(res){
            var setting = {
                view: {
                    showLine: true,
                    selectedMulti: false,
                    dblClickExpand: false,
                    showIcon: false
                },
                data: {
                    key : {
                        name : 'name'
                    },
                    simpleData : {
                        enable: true,
                        idKey : "code",
                        pIdKey : "pid",
                        rootPId : "-1"
                    }
                }
            };
            var organizationTree = $('#zone_float').lonixFloat({
                source : res,
                setting : setting,
                searchField : 'name',
                target : $('#zone_name'),
                primary : function (nodes) {
                    var node = nodes[0];
                    var codes = node.code;
                    var names = '';
                    while (true) {
                        if (names == '') {
                            names = node.name;
                        } else {
                            names = node.name + '-' + names;
                        }
                        if (!node.getParentNode() || node.getParentNode().level == 0) {
                            break;
                        }
                        node = node.getParentNode();
                    }
                    $('#zone_name').val(names);
                    $('#zone_id').val(codes);
                    $('#zone_type').val(node.type);
                    $('#zone_float').fadeUp();
                    $this.findData();
                }
            });
            $this.organizationTree = organizationTree;
        });

        $this.initTable();
        $this.findData();
    },
    /**
     * 下一条
     */
    nextData:function(e){
        $this = $(e.target).data('that');
        var grid = $this.$parent.find('#inspection-list').data('kendoGrid');
        //获取当前选中行
        var selectedTr = grid.select();
        var indexOf = 0;
        if(selectedTr.length != 0){
            indexOf = selectedTr.prevAll().length + 1;
        }
        var row = grid.tbody.find(">tr:not(.k-grouping-row)").eq(indexOf);
        if(row.length <= 0 ) return;
        grid.select(row);
    },
    limitProvince : function (t, e) {
        if (e.keyCode >= 65 && e.keyCode <= 90) {
            var list = this.provinceMap.get(e.key);
            if (!isEmpty(list) && list.length > 0) {
                this.curList = list;
                $(t).val(list[0]);
                t.select();
                $(t).attr('data-index', 0);
            }
        } else if (e.keyCode == 108 || e.keyCode == 13) {
            if ('京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新'.indexOf($(t).val())!=-1) {
                $(t).next().focus();
                $(t).next()[0].select();
            }
        } else {
            if (!isEmpty(this.curList) && this.curList.length > 0) {
                var index = $(t).attr('data-index');
                if (!isEmpty(index) && !isNaN(index)) {
                    if (e.keyCode == 38) {
                        if (index > 0) {
                            $(t).attr('data-index', --index);
                            $(t).val(this.curList[index]);
                            t.select();
                        }
                    } else if (e.keyCode == 40) {
                        if (index < this.curList.length -1) {
                            $(t).attr('data-index', ++index);
                            $(t).val(this.curList[index]);
                            t.select();
                        }
                    }
                }
            }
        }
        e.returnValue = false;
        e.stopPropagation = true;
        return false;
    },
    limitVehicleNumber : function (t, e) {
        if (e.keyCode == 8) {
            if ($(t).val().length == 0) $(t).prev().focus();
            return true;
        } else {
            if ((e.keyCode >= 48 && e.keyCode <= 90) || (e.keyCode >= 96 && e.keyCode <= 105)) {
                var str = e.key.toUpperCase();
                $(t).val(str);
                $(t).next().focus();
            }
        }
        e.returnValue = false;
        e.stopPropagation = true;
        return false;
    },
    reset : function (e) {
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.models.bindFieldArray);
        $('#zone_id').val('');
        $('#zone_type').val('');
    },
    choiceCount : function (a) {
        $(a).parent().find('button').removeClass('action');
        $(a).parent().find('input[type="number"]').removeClass('action');
        $(a).addClass('action');
        this.beforeCount = $(a).val();
        this.searchVehicle();
    },
    choiceAfterCount : function (a) {
        $(a).parent().find('button').removeClass('action');
        $(a).parent().find('input[type="number"]').removeClass('action');
        $(a).addClass('action');
        this.afterCount = $(a).val();
        this.searchVehicle();
    },
    choiceType : function (a) {
        $(a).parent().find('button').removeClass('action');
        $(a).addClass('action');
        this.findData();
    },
    choiceDate : function (a) {
        $(a).parent().find('button').removeClass('action');
        $(a).addClass('action');
        var type = $(a).val();
        var today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setSeconds(0);
        var beginTime;
        if (type == 0) {
            beginTime = today;
            this.sysUtils.mvvmModel.set('beginTime', beginTime.pattern('yyyy-MM-dd HH:mm:ss'));
            today.setHours(23);
            today.setMinutes(59);
            today.setSeconds(59);
            this.sysUtils.mvvmModel.set('endTime', today.pattern('yyyy-MM-dd HH:mm:ss'));
        } else if (type == -1) {
            this.sysUtils.mvvmModel.set('beginTime', '');
            this.sysUtils.mvvmModel.set('endTime', '');
        } else if (type == -2) {
            beginTime = new Date();
            beginTime.setYear(beginTime.getFullYear()-1);
            beginTime.setHours(0);
            beginTime.setMinutes(0);
            beginTime.setSeconds(0);
            today.setHours(23);
            today.setMinutes(59);
            today.setSeconds(59);
            this.sysUtils.mvvmModel.set('beginTime', beginTime.pattern('yyyy-MM-dd HH:mm:ss'));
            this.sysUtils.mvvmModel.set('endTime', today.pattern('yyyy-MM-dd HH:mm:ss'));
        } else {
            beginTime = new Date();
            beginTime.setDate(beginTime.getDate()-type);
            beginTime.setHours(0);
            beginTime.setMinutes(0);
            beginTime.setSeconds(0);
            today.setHours(23);
            today.setMinutes(59);
            today.setSeconds(59);
            this.sysUtils.mvvmModel.set('beginTime', beginTime.pattern('yyyy-MM-dd HH:mm:ss'));
            this.sysUtils.mvvmModel.set('endTime', today.pattern('yyyy-MM-dd HH:mm:ss'));
        }
        this.findData();
    },
    initTable : function () {
        var $this = this;
        var columns = [
            {
                width:30,
                headerTemplate : '<input type="checkbox" gridId="inspection-list" onclick="gridCheckAll(this)" />',
                template : '<input type="checkbox" name="id" value="${id}" />'
            },
            {
                title : '车牌号',
                width : 105,
                field : 'vehicleNo'
            },
            {
                title : '入场时间',
                field : 'inTime'
            },
            {
                title : '可信度',
                width : 60,
                field : 'inImgTrust'
            },
            {
                title : '状态',
                width : 60,
                template : '# if (hasCorrect == 0) {# 未处理 # } else if (hasCorrect == 1) { # 被矫正 # } else if (hasCorrect == 2) { # 归档 # } #'
            }
        ];
        var a = 0;
        $this.sysUtils.createGird($this.$parent.find('#inspection-list'), {
            selectable : 'single',
            autoSync : true,
            columnsMenu : true,
            pageable : {input : true, numeric : false},
            columns : columns,
            change : function(e) {
                $this.selectRowId = this.dataItem(this.select()).id;
                $this.findDetail($this.selectRowId);
            },
            dataBound : function () {
                if (a == 0) {
                    var row = this.tbody.find(">tr:not(.k-grouping-row)").eq(0);
                    if(row.length <= 0 ) return;
                    this.select(row);
                    a = 1;
                }
            }
        });
    },
    findDetail : function (id) {
        if (isEmpty(id)) {
            notification({'title':'错误', 'message':'请先选择左侧数据'}, 'error');
            return;
        }
        var $this = this;
        var beforeCount = $this.$parent.find('#before-record-count button.action').val() || $this.$parent.find('#before-record-count input[type="number"].action').val();
        var afterCount = $this.$parent.find('#after-record-count button.action').val() || $this.$parent.find('#after-record-count input[type="number"].action').val();
        JsonpAjax(baseApiPath + 'recordMarket/inspection/detail/' + id + '?beforeCount='+beforeCount+'&afterCount='+afterCount, '', 'json', function(res) {
            $this.$parent.find('.magnifier-line li').not('#eg-image').remove();
            $this.$parent.find('.magnifier-line #eg-image').show();
            if (!isEmpty(res)) {
                if (res.entity.inParkType == '无牌车放行') {
                    $this.$parent.find('#vehicle-no').html('无牌车');
                } else {
                    var vehicleNo = res.entity.vehicleNo;
                    $this.$parent.find('#vehicle-no').html(vehicleNo);
                    $this.$parent.find('.plateNumber input[type=text]').each(function(inx, itm) {
                        $(itm).val(vehicleNo.charAt(inx));
                    });
                }
                $this.$parent.find('.timeContrast .sp2').html(res.entity.inTime);
                $this.$parent.find('#vehicle-type').html(Utils.getModelNameByParentKey(BASIS.VEHICLE_TYPE.ROOT, res.entity.vehicleType));
                var imageList = res.imgList;
                if (!isEmpty(imageList)) {
                    $this.$parent.find('.magnifier-line #eg-image').hide();
                    for (var i = 0; i < imageList.length; i++) {
                        var li = $this.$parent.find('.magnifier-line #eg-image').clone(true);
                        li.show();
                        li.removeAttr('id');
                        li.find('img').attr('src', (imgServerUrl + '/' + imageList[i].imgUrl));
                        $this.$parent.find('.magnifier-line ul').append(li);
                    }
                    $this.$parent.find('.magnifier-line li').not('#eg-image').find('div').trigger('click');
                }
                $this.findByVehicle(res.entity.vehicleNo);
            }
        });
    },
    searchVehicle : function (e) {

        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        var vehicleNo = '';
        $this.$parent.find('.plateNumber input[type="text"]').each(function (inx, itm) {
            vehicleNo += $(itm).val();
        });
        if (isEmpty(vehicleNo)) {
            notification({'title':'警告', 'message':'请先输入车牌！'}, 'error');
            $this.$parent.find('.plateNumber input:eq(0)').focus();
            return;
        }
        $this.findByVehicle(vehicleNo);
    },
    findByVehicle : function (vehicleNo) {
        var $this = this;
        if (isEmpty($this.beforeCount)) {
            $this.beforeCount = 5
        }
        if (isEmpty($this.afterCount)) {
            $this.afterCount = 5;
        }
        JsonpAjax(baseApiPath + 'recordMarket/inspection/record/' + vehicleNo + '?beforeCount=' + $this.beforeCount+'&afterCount='+$this.afterCount, '', 'json', function (res) {
            var beforeList = res.beforeList;
            $this.$parent.find('#before-record-list tr').not('#eg-record').remove();
            if (isEmpty(beforeList) || beforeList.length == 0) {
                $this.$parent.find('#before-record-list').append('<tr><td colspan="8" style="text-align: center; font-size:14px;">暂无相关数据</td></tr>');
            } else {
                for (var i = 0; i < beforeList.length; i++) {
                    var tr = $this.$parent.find('#eg-record').clone(true);
                    tr.removeAttr('id');
                    tr.attr('data-value', beforeList[i].id);
                    tr.find('td:eq(2)').html(beforeList[i].inTime);
                    tr.find('td:eq(4)').html(beforeList[i].inPartitionCode);
                    tr.find('td:eq(6)').html(Utils.getModelNameByParentKey(BASIS.TRAFFIC_TYPE_CLASS.ROOT, beforeList[i].credentialsType));
                    $this.$parent.find('#before-record-list').append(tr);
                }
            }

            var afterList = res.afterList;
            $this.$parent.find('#after-record-list tr').remove();
            if (isEmpty(afterList) || afterList.length == 0) {
                $this.$parent.find('#after-record-list').append('<tr><td colspan="8" style="text-align: center; font-size:14px;">暂无相关数据</td></tr>');
                if (!isEmpty(beforeList) && beforeList.length > 0) {
                    $this.$parent.find('#new_record tr').remove();
                    var tr = $this.$parent.find('#eg-record').clone(true);
                    tr.removeAttr('id');
                    tr.attr('data-value', beforeList[0].id);
                    tr.find('td:eq(2)').html(beforeList[0].inTime);
                    tr.find('td:eq(4)').html(beforeList[0].inPartitionCode);
                    tr.find('td:eq(6)').html(Utils.getModelNameByParentKey(BASIS.TRAFFIC_TYPE_CLASS.ROOT, beforeList[0].credentialsType));
                    $this.$parent.find('#new_record').append(tr);
                } else {
                    $this.$parent.find('#new_record tr').remove();
                    var tr = $this.$parent.find('#eg-record').clone(true);
                    tr.removeAttr('id');
                    tr.attr('data-value', res.entity.id);
                    tr.find('td:eq(2)').html(res.entity.inTime);
                    tr.find('td:eq(4)').html(res.entity.inPartitionCode);
                    tr.find('td:eq(6)').html(Utils.getModelNameByParentKey(BASIS.TRAFFIC_TYPE_CLASS.ROOT, res.entity.credentialsType));
                    $this.$parent.find('#new_record').append(tr);
                }
            } else {
                for (var i = 0; i < afterList.length; i++) {
                    var tr = $this.$parent.find('#eg-record').clone();
                    tr.removeAttr('id');
                    tr.attr('data-value', afterList[i].id);
                    tr.find('td:eq(2)').html(afterList[i].inTime);
                    tr.find('td:eq(4)').html(afterList[i].inPartitionCode);
                    tr.find('td:eq(6)').html(Utils.getModelNameByParentKey(BASIS.TRAFFIC_TYPE_CLASS.ROOT, afterList[i].credentialsType));
                    $this.$parent.find('#after-record-list').append(tr);
                }
                $this.$parent.find('#new_record tr').remove();
                var tr = $this.$parent.find('#eg-record').clone(true);
                tr.removeAttr('id');
                tr.attr('data-value', beforeList[i].id);
                tr.find('td:eq(2)').html(beforeList[0].inTime);
                tr.find('td:eq(4)').html(beforeList[0].inPartitionCode);
                tr.find('td:eq(6)').html(Utils.getModelNameByParentKey(BASIS.TRAFFIC_TYPE_CLASS.ROOT, beforeList[0].credentialsType));
                $this.$parent.find('#new_record').append(tr);
            }
        });
    },
    findData : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        var params = $this.sysUtils.getBindDocJson($this.models.bindFieldArray);
        var reliability = $this.$parent.find('#reliability button.action').val();
        var trafficType = $this.$parent.find('#traffic-type button.action').val();
        var organizationCode = $this.$parent.find('#zone_id').val();
        var organizationType = $this.$parent.find('#zone_type').val();
        var recordStatus = '';
        $this.$parent.find('[name="display_record_status"]').each(function (inx, itm) {
            if (itm.checked) {
                recordStatus += itm.value + ',';
            }
        });
        if (!isEmpty(recordStatus)) {
            recordStatus = recordStatus.substring(0, recordStatus.length - 1);
        }
        params['reliability'] = reliability;
        params['trafficType'] = trafficType;
        params['recordStatus'] = recordStatus;
        params['organizationCode'] = isEmpty(organizationCode) ? undefined : organizationCode;
        params['organizationType'] = isEmpty(organizationType) ? undefined : organizationType;
        var dataT = {jsonParam:JSON.stringify(params)};
        var dataSource = $this.sysUtils.getDataSource({url : baseApiPath + 'recordMarket/inspection/list', data : dataT, dataType : 'odata'});
        var grid = $this.$parent.find('#inspection-list').data('kendoGrid');
        grid.setDataSource(dataSource);
    },
    primaryData : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        if (isEmpty($this.selectRowId)) {
            notification({'title':'警告', 'message':'请先选择需要确认的数据'}, 'error');
            return;
        }
        JsonpAjax(baseApiPath + 'recordMarket/inspection/primary/' + $this.selectRowId, '', 'json', function (res) {
            $this.findData();
            $this.selectRowId = undefined;
        }, false);
    },
    correctData : function (e) {
        var $this =this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        if (isEmpty($this.selectRowId)) {
            notification({'title':'警告', 'message':'请先选择左侧的数据！'}, 'error');
            return;
        }
        var vehicleNo = '';
        $this.$parent.find('.plateNumber input[type="text"]').each(function(inx, itm){
            vehicleNo += $(itm).val();
        });
        var vehicleType = $this.$parent.find('#choice-vehicle-type').val();
        var jsonData = {'vehicleNo':vehicleNo, 'vehicleType':vehicleType};
        JsonpAjax(baseApiPath + 'recordMarket/inspection/correct/' + $this.selectRowId, JSON.stringify(jsonData), 'json', function(res) {
            $this.findData();
            $this.selectRowId = undefined;
        });
    },
    cancelData : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        var id = $this.selectRowId;
        if (isEmpty(id)) {
            notification({'title':'警告', 'message':'请先选择左侧的数据！'}, 'error');
            return;
        }
        var jsonData = {'ids':id};
        JsonpAjax(baseApiPath + 'recordMarket/updateStatus', JSON.stringify(jsonData), 'json', function (res) {
            $this.findData();
            $this.selectRowId = undefined;
        });
    },
    searchImage : function (btn, event) {
        var $this = this;
        var id = $(btn).parents('tr').attr('data-value');
        JsonpAjax(baseApiPath + 'recordMarket/inspection/detail/' + id, '', 'json', function (res) {
            $this.selectImages = res.imgList;
            $this.searchImageDiv = $this.sysUtils.openWindow($this.searchImageDiv, {
                title : '查看图片',
                width : '510px',
                height: '630px',
                resizeable : false,
                content : 'views/parkLotCenter/managerCenter/vehicleinspection_image.html'
            }, true);
        });
    }
}

var VehicleInspectionImageDetail = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
VehicleInspectionImageDetail.prototype = {
    init : function () {
        var $this = this;
        var fieldArray = [];
        var functionArray = [];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        this.loadImage();
    },
    loadImage : function () {
        var $this = this;
        if (isEmpty(inspectionManager.selectImages)) {
            notification({'title':'警告', 'message':'该条通行记录的图片或已被删除'},'error');
            return;
        }
        var list = inspectionManager.selectImages;
        for (var i = 0; i < list.length; i++) {
            $this.$parent.find('.imageBox img:eq('+i+')').attr('src', '');
        }
        inspectionManager.selectImages = undefined;
    }
}